package org.example.messages;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class Producer {

    public static void main(String[] args){
        // 1.获取连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.56.108");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = null;
        Channel channel = null;
        try {
            // 2.创建连接
            connection = connectionFactory.newConnection();

            // 3.通过connection创建Channel
            channel = connection.createChannel();
            // 自定义属性
            Map<String, Object> heads = new HashMap<>();
            heads.put("my1","my1");
            heads.put("my2","my2");
            AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                    .deliveryMode(2)    //deliveryMode : 1不持久化，2持久化
                    .contentEncoding("utf-8")
                    .expiration("10000")
                    .headers(heads)
                    .build();

            // 4.通过channel发送数据
            for (int i = 0; i <5 ; i++) {
                String str = "hello rabbitmq"+i;
                channel.basicPublish("","test001",props,str.getBytes());
            }
            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }


    }
}
